package logic

import (
	"context"
	"zhongwen/models/mysql"

	"zhongwen/zhongwenrpc/internal/svc"
	"zhongwen/zhongwenrpc/zhongwenrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelListLogic {
	return &NovelListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NovelListLogic) NovelList(in *zhongwenrpc.NovelListRequest) (*zhongwenrpc.NovelListResponse, error) {
	// todo: add your logic here and delete this line
	var noveldata []mysql.NovelData
	offset := (in.Page - 1) * in.Size
	mysql.DB.Debug().Model(&mysql.Novel{}).Select("novels.*, classes.NAME AS class_name").
		Joins("LEFT JOIN collects ON novels.id = collects.novel_id").
		Joins(" LEFT JOIN classes ON classes.id = novels.class_id").Order("novels.created_at desc").
		Offset(int(offset)).Limit(int(in.Size)).Find(&noveldata)

	var novelList []*zhongwenrpc.NovelList
	for _, data := range novelList {
		list := zhongwenrpc.NovelList{
			Title:      data.Title,
			Info:       data.Info,
			CollectNum: data.CollectNum,
			ClassName:  data.ClassName,
			UserName:   data.UserName,
			NovelId:    data.NovelId,
		}
		novelList = append(novelList, &list)
	}
	return &zhongwenrpc.NovelListResponse{
		List: novelList,
	}, nil
}
